import React from 'react';
import {Button, Icon, Tree, Spin, message} from 'antd';
import {WeaTools, WeaDialog, WeaSearchGroup, WeaFormItem, WeaInputNumber,WeaInput, WeaSelect, WeaHelpfulTip,WeaLocaleProvider, WeaCheckbox} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import * as lodash from 'lodash';
import EOrderCol from './base/EOrderCol'
import EField_New from './base/EField_New'
import EMoreAddress from './base/EMoreAddress'
const TreeNode = Tree.TreeNode;

// 流程中心，数据来源
class Content_8_DataSource extends React.Component {
    constructor(props) {
        super(props);
        this.getButtons = this.getButtons.bind(this);
        this.getTreeData = this.getTreeData.bind(this);
        this.getTreeNodes = this.getTreeNodes.bind(this);
        this.onLoadData = this.onLoadData.bind(this);
        this.onExpand = this.onExpand.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);

        const {tabNew = {}, tabData = {}} = props;

        const {workflowSource = {}} = tabData;
        const {typeids, flowids, nodeids} = workflowSource;

        const wftypeCheckedKeys = typeids ? typeids.split(',').map(item => 'wftype_' + item) : [];
        const wfCheckedKeys = flowids ? flowids.split(',').map(item => 'wf_' + item) : [];
        const nodeCheckedKeys = nodeids ? nodeids.split(',').map(item => 'node_' + item) : [];

        const viewType = tabData.viewType || tabNew.viewType.selected;
        const isShowNodeBtn = viewType == '1' || viewType == '2' || viewType == '4';  // 待办、已办和我的请求显示是否开启节点按钮
        const hasNodeData = !!nodeids;

        this.state = {
            visible: true,
            id: tabData.id,
            title: tabData.title || '',
            viewType: viewType,
            isComplete: tabData.isComplete || '0',
            showCopy: tabData.showCopy || '1',
            showCount: tabData.showCount || '0',
            isArrangement: tabData.isArrangement || '0',
            orderColVisible: false,
            eFieldNewVisible: false,
            orderColDataSource: lodash.isEmpty(tabData.orderColDataSource) ? tabNew.orderColDataSource : tabData.orderColDataSource,
            orderColUsedKeys: tabData.orderColUsedKeys || [],
            isExclude: tabData.isExclude || tabNew.isExclude.selected,
            workflowSource: workflowSource,
            treeLoading: false,
            treeData: [],
            checkedKeys: {checked: [...wftypeCheckedKeys, ...wfCheckedKeys, ...nodeCheckedKeys], halfChecked: []},
            expandedKeys: wftypeCheckedKeys,
            isShowNodeBtn: isShowNodeBtn,
            isNeedNode: hasNodeData,
            hasNodeData: hasNodeData,
            eFieldNewDataSource: tabData.eFieldNewDataSource || tabNew.eFieldNewDataSource,
            eFieldNewUsedKeys: tabData.eFieldNewUsedKeys || [],
            scrollDirection: tabData.scrollDirection || tabNew.scrollDirection.selected,
            showView: tabData.showView || 1,
            showReject: tabData.showReject || 1,
            showTimeout: tabData.showTimeout,
            showNoReply: tabData.showNoReply || '1',
            showForward: tabData.showForward || '1',
            showCY: tabData.showCY || '1',
            scrollSpeed: tabData.scrollSpeed || '20',
            eMoreAddress: props.tabData.eMoreAddress|| '',
            eMoreShowType: props.tabData.eMoreShowType|| '0',
        };
    }
    componentWillMount() {
        const {isExclude, isShowNodeBtn, hasNodeData, viewType} = this.state;
        if (isExclude != '2') { // 选择或排除选择
            this.getTreeData(isShowNodeBtn && hasNodeData, viewType, isExclude);
        }
    }

    render() {
        const {tabNew} = this.props;
        const { esettingDatas } = tabNew;
        const {
            visible, title, viewType, isComplete, showCopy, isArrangement, showCount,
            orderColVisible, eFieldNewVisible, orderColDataSource, orderColUsedKeys, showTimeout,
            isExclude, treeLoading, treeData, checkedKeys, expandedKeys, isShowNodeBtn, isNeedNode, hasNodeData,
            eFieldNewDataSource, eFieldNewUsedKeys,scrollDirection, showView, showReject, showNoReply, status, showForward, showCY,
            eMoreAddress, eMoreShowType
        } = this.state;
        const field = {showView: showView, showReject: showReject,showTimeout: showTimeout, isArrangement: isArrangement, showNoReply: showNoReply, showCopy: showCopy, showForward: showForward, showCY: showCY};
        const fieldTitle = {showView: getLabel(391236,"勾选后，显示包含“转发给我”、“抄送给我”这些提交或查看均不影响流程流转的流程"),
            showReject: getLabel(391237,"勾选后，显示包含退回给“我”的流程"),showTimeout: getLabel(391238,"勾选后，将优先显示超时流程，再按设置的排序字段排序")};
        let orderColComp = <div></div>;
        if (orderColVisible) {
            const orderColProps = {
                orderColDataSource: _.cloneDeep(orderColDataSource),
                orderColUsedKeys: _.cloneDeep(orderColUsedKeys),
                onOk: (data) => {
                    this.setState({
                        orderColDataSource: data.orderColDataSource,
                        orderColUsedKeys: data.orderColUsedKeys,
                        orderColVisible: false
                    });
                },
                onCancel: () => {
                    this.setState({
                        orderColVisible: false
                    });
                }
            };
            orderColComp = <EOrderCol ecId={`${this && this.props && this.props.ecId || ''}_EOrderCol@exhxun`} {...orderColProps}/>
        }
        let _scrollSpeed=this.state.scrollSpeed;
        if(this.state.scrollSpeed==undefined){
            _scrollSpeed=20;
        }
        let EFieldNew = <div></div>;
        if (eFieldNewVisible) {
            const eFieldNewProps = {
                eFieldNewDataSource: _.cloneDeep(eFieldNewDataSource),
                eFieldNewUsedKeys: _.cloneDeep(eFieldNewUsedKeys),
                onOk: (data) => {
                    this.setState({
                        eFieldNewDataSource: _.cloneDeep(data.eFieldNewDataSource),
                        eFieldNewUsedKeys: _.cloneDeep(data.eFieldNewUsedKeys),
                        eFieldNewVisible: false
                    });
                },
                onCancel: () => {
                    this.setState({
                        eFieldNewVisible: false
                    });
                }
            };
            EFieldNew = <EField_New ecId={`${this && this.props && this.props.ecId || ''}_EField_New@njfmed`} {...eFieldNewProps}/>
        }

        const orderColUsedNames = [];
        for (let i = 0, len = orderColUsedKeys.length; i < len; i++) {
            for (let j = 0, len2 = orderColDataSource.length; j < len2; j++) {
                if (orderColUsedKeys[i] == orderColDataSource[j].key) {
                    orderColUsedNames.push(orderColDataSource[j].fieldName + '-' + (orderColDataSource[j].orderType == '0' ? getLabel(340,"降序") : getLabel(339,"升序")));
                }
            }
        }

        const eFieldNewUsedNames = [];
        for (let i = 0; i < eFieldNewUsedKeys.length; i++) {
            for (let j = 0 ; j < eFieldNewDataSource.length; j++) {
                if (eFieldNewUsedKeys[i] == eFieldNewDataSource[j].key) {
                    eFieldNewUsedNames.push(eFieldNewDataSource[j].name);
                }
            }
        }

        let orderTitles ="";
        for(let i = 0;i < orderColUsedNames.length; i++){
            orderTitles = orderTitles + orderColUsedNames[i];
        }

        let eFieldTitles ="";
        for(let i = 0;i < eFieldNewUsedNames.length; i++){
            eFieldTitles = eFieldTitles + eFieldNewUsedNames[i];
        }
        let spanWidth = '92px';
        let divWidth = '136px';
        if(esettingDatas[viewType] && esettingDatas[viewType].typesetting.typedatas && esettingDatas[viewType].typesetting.typedatas.length <= 1){
            spanWidth = 'auto';
            divWidth = 'auto';
        }
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@kt9teh`}
                className="portal-esetting-dialog"
                visible={visible}
                title={getLabel(19480, '内容设置')}
                icon="icon-coms-portal"
                iconBgcolor='#1a57a0'
                style={{ width: '700px', height: $(document).height()+ "px"}}
                resize={true}
                hasScroll={true}
                buttons={this.getButtons()}
                onCancel={this.onCancel}
            >
                <div style={{minHeight:'440px'}}>
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@tlmx5a`} title={getLabel(33396, '设置项')} needTigger={true} showGroup={true} style={{maxHeight: parseInt(window.innerHeight) - 300 + 'px'}}>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2octff`} label={getLabel(24986, '标题')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@aqfta7`} inputType="multilang" isBase64={true} value={title} viewAttr={3} onChange={value => this.setState({title: value})}/>
                        </WeaFormItem>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@p5cauh`} label={getLabel(17483, '查看类型')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            <div style={{width: '100%'}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@h0vaeu`}
                                    options={esettingDatas.options}
                                    value={viewType}
                                    onChange={value => {
                                        const isShowNodeBtn = (value == '1' || value == '2' || value == '4');
                                        this.getTreeData(isShowNodeBtn && hasNodeData, value);
                                        this.setState({
                                            viewType: value,
                                            isShowNodeBtn: isShowNodeBtn,
                                            showCount: '0',
                                            showView: '1',
                                            showReject: '0',
                                            showTimeout: '0',
                                        });
                                    }}
                                />
                            </div>
                            {
                                esettingDatas[viewType] && esettingDatas[viewType].typesetting && <div style={{marginTop: '10px'}}>
                                    {
                                        esettingDatas[viewType].typesetting.typedatas ? esettingDatas[viewType].typesetting.typedatas.map(item => {
                                            return  <div style={{ "top": "3px",position: "relative","width": divWidth, "display": 'inline-block'}}>
                                                <div style={{display: 'inline-block'}}><WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@nopmv4@${item.field}`}
                                                    value={field[item.field] || item.defaultVal}
                                                    onChange={value => {
                                                        this.setState({[item.field]: value})
                                                    }}

                                                /></div>
                                                <span style={{margin: '0px 4px -3px 7px', width: spanWidth, overflow:" hidden",textOverflow: 'ellipsis', whiteSpace:" nowrap", display: 'inline-block'}} title={item.labelname}>{item.labelname}</span>{item.field != 'isArrangement' && fieldTitle[item.field] && <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@abqu4s@${item.field}`} title={fieldTitle[item.field]}/>}
                                            </div> }): <div style={{width: '100px'}}>
                                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@g07bse`}
                                                options={esettingDatas[viewType].typesetting.option}
                                                value={isComplete} onChange={value => this.setState({isComplete: value})}>
                                            </WeaSelect>
                                        </div>
                                    }
                                </div>
                            }
                        </WeaFormItem>
                        {
                            esettingDatas[viewType] && esettingDatas[viewType].showcount && <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@exiqus`} label={getLabel(390629, '显示数量 ')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                                <div style={{height: '30px'}}>
                                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@t56c0u`} options={esettingDatas[viewType].showcount.option} detailtype={3} value={showCount} onChange={value => {this.setState({showCount: value})}}/>
                                </div>
                            </WeaFormItem>
                        }
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8b4mik`} label={getLabel(19495, '显示字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            {EFieldNew}
                            <div style={{height: '30px', lineHeight: '23px'}}>
                                <i className="icon-coms-Flow-setting portal-esetting-btn" style={{position: "relative", zIndex: "12"}} onClick={() => this.setState({eFieldNewVisible: true})}/>
                                <span className="pottal-element-showfield" title={eFieldTitles}>&nbsp;&nbsp;&nbsp;&nbsp;{eFieldNewUsedNames.join('，')}</span>
                            </div>
                        </WeaFormItem>

                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@yuwvpy`} label={getLabel(15512, '排序字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            {orderColComp}
                            <div style={{height: '30px', lineHeight: '23px'}}>
                                <i className="icon-coms-Flow-setting portal-esetting-btn"  style={{position: "relative", zIndex: "12"}} onClick={() => this.setState({orderColVisible: true})}/>
                                <span className="pottal-element-ordercol" title={orderTitles}>&nbsp;&nbsp;&nbsp;&nbsp;{orderColUsedNames.join('，')}</span>
                            </div>
                        </WeaFormItem>
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@umzrn6`} label={getLabel(20281, '滚动方向')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            <div style={{width: '100px'}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@p57gls`}
                                    options={
                                        tabNew.scrollDirection.options.map((item) => {
                                            return {key: item.key, selected: false, showname: item.value};
                                        })
                                    }
                                    value={scrollDirection}
                                    onChange={value => {
                                        this.setState({scrollDirection: value});
                                    }}
                                />
                            </div>
                        </WeaFormItem>
                        {
                            (scrollDirection == 'Down' || scrollDirection == 'Up') && <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1hatjn`} label={getLabel(22927, '滚动速度')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                                <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@lhehg8`}
                                    value={_scrollSpeed}
                                    style={{width: '100px'}}
                                    onChange={value => {
                                        this.setState({scrollSpeed:  value=='0'?20:value});
                                    }}
                                    min={0}
                                />
                                <span style={{ position: 'relative'}}>ms</span>
                            </WeaFormItem>
                        }
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@r03eo9`} label={getLabel(21672, '流程来源')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                            <div style={{width: '100%'}}>
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@stbjy5`}
                                    options={
                                        tabNew.isExclude.options.map((item) => {
                                            return {key: item.key, selected: false, showname: item.value};
                                        })
                                    }
                                    value={isExclude}
                                    onChange={value => {
                                        this.setState({isExclude: value});
                                        if(isExclude == '2') this.setState({workflowSource: {}})
                                        if (value != '2') {
                                            this.getTreeData(isShowNodeBtn && hasNodeData, viewType, value);
                                        }
                                    }}
                                />
                            </div>
                            {
                                isExclude != '2' ?
                                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@6pf1ns`} spinning={treeLoading}>
                                        <div style={{width: '465px', height: '300px', overflow: 'auto',msOverflowStyle:'auto'}}>
                                            {
                                                isExclude != '3' && isExclude !='4' &&<div style={{display: isShowNodeBtn ? 'block' : 'none', position: 'absolute', top: '10px', right: '20px'}}>
                                                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dubo7n`} size="small" title={isNeedNode ? getLabel(386556, '包含节点') : getLabel(386557, '不包含节点')} onClick={() => this.getTreeData(!isNeedNode, viewType)}>
                                                        <i className={isNeedNode ? 'icon-coms-DisplaySubordinates' : 'icon-coms-NoDisplayOfSubordinates'} style={{color: isNeedNode ? 'rgb(45, 183, 245)' : ''}}/>
                                                    </Button>
                                                </div>
                                            }
                                            <Tree ecId={`${this && this.props && this.props.ecId || ''}_Tree@tstdvd`}
                                                checkable={true}
                                                checkStrictly={true}
                                                expandedKeys={expandedKeys}
                                                checkedKeys={checkedKeys}
                                                onExpand={this.onExpand}
                                                loadData={this.onLoadData}
                                                onCheck={this.onCheck}
                                            >
                                                {this.getTreeNodes(treeData)}
                                            </Tree>
                                        </div>
                                    </Spin>
                                    : ''
                            }
                        </WeaFormItem>
                        <EMoreAddress ecId={`${this && this.props && this.props.ecId || ''}_EMoreAddress@e1w6ou`} ref="eMoreAddress" eMoreAddress={eMoreAddress} eMoreShowType={eMoreShowType}/>
                    </WeaSearchGroup>
                </div>
            </WeaDialog>
        );
    }

    getButtons() {
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9jgahw`} type="primary" onClick={this.onOk}>{getLabel(826, '确定')}</Button>);
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5h5t8x`} type="ghost" onClick={this.onCancel}>{getLabel(31129, '取消')}</Button>);
        return buttons;
    }

    getTreeData(isNeedNode, viewType, isExclude) {
        this.setState({treeLoading: true, isNeedNode: isNeedNode});
        let api = '/api/public/browser/data/-99991';
        if(isExclude == '3' || isExclude =='4') {
            api = '/api/portal/workFlowType/getWorkFlowTypeDatas';
        }
        WeaTools.callApi(api || '/api/public/browser/data/-99991', 'GET', {
            isWfTree: 1,
            needNode: isNeedNode ? 1 : 0,
            containsOfs: 1,
            viewtype: viewType
        }).then(data => {
            if(isExclude == '3' || isExclude =='4') {
                this.setState({treeLoading: false, treeData: data.wfType.datas});
            }else {
                this.setState({treeLoading: false, treeData: data.datas.subs});
            }

            if (isNeedNode && isExclude != '3' && isExclude =='4') {
                const {workflowSource} = this.state;
                const {flowids = ''} = workflowSource;
                const flowidarr = flowids.split(',');
                if (flowidarr && flowidarr.length) {
                    for (let i = 0, len = flowidarr.length; i < len; i++) {
                        this.onLoadData({props: {id: flowidarr[i]}}, true);
                    }
                }
            }
        });
    }

    getTreeNodes(treeData) {
        const loop = (data, pids) => {
            return data.map((item) => {
                const _pids = _.cloneDeep(pids);
                _pids.push(item.type + '_' + item.id);

                const children = item.subs;
                if (children && children.length) {
                    return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@pccp8x@${item.type + '_' + item.id}`} key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}>{loop(children, _pids)}</TreeNode>;
                } else {
                    return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@nlvevy@${item.type + '_' + item.id}`} key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}/>;
                }
            });
        };

        return loop(treeData, []);
    }

    onLoadData(node, isInit) {
        const {id} = node.props;

        if (!isInit) {
            this.setState({treeLoading: true});
        }

        WeaTools.callApi('/api/public/browser/data/-99991', 'GET', {
            isWfTree: 1,
            needNode: 1,
            type: 'wf',
            id: id
        }).then(data => {
            const loop = (treeData, pid, data) => {
                for (let i = 0, len = treeData.length; i < len; i++) {
                    if (treeData[i].id == pid && treeData[i].type == 'wf') {
                        treeData[i].subs = data || [];
                        break;
                    } else {
                        const children = treeData[i].subs;
                        if (children && children.length) {
                            loop(children, pid, data);
                        }
                    }
                }
            };

            const {treeData, expandedKeys} = this.state;
            loop(treeData, id, data.datas);
            this.setState({treeLoading: false, treeData: treeData, expandedKeys: [...expandedKeys, 'wf_' + id]});
        });
    }

    onExpand(expandedKeys) {
        this.setState({expandedKeys: expandedKeys});
    }

    onCheck(checkedKeys, e) {
        const {eventKey, pids, children = []} = e.node.props;
        const childrenKeys = this.getChildrenKeys(children);
        let grandSonKey = '';
        children.map(item => {
            if(item.props.children){
                let itemChildren = this.getChildrenKeys(item.props.children);
                if(itemChildren) {
                    grandSonKey = grandSonKey + ',' +itemChildren;
                };
            };
        })
        let grandSonKeys = grandSonKey.split(',');
        let checked = [];
        if (e.checked) {
            checked = _.concat(...pids, ...childrenKeys, ...grandSonKeys, checkedKeys.checked);
        } else {
            checked = _.pullAll(checkedKeys.checked, _.concat(childrenKeys,grandSonKeys));
        }
        const _checked = _.uniq(checked);

        const {isShowNodeBtn, isNeedNode} = this.state;

        let typeids = '', flowids = '', nodeids = '';
        for (let i = 0, len = _checked.length; i < len; i++) {
            const _keys = _checked[i].split('_');
            if (_keys[0] == 'wftype') {
                typeids += _keys[1] + ',';
            } else if (_keys[0] == 'wf') {
                flowids += _keys[1] + ',';
            } else if (isShowNodeBtn && isNeedNode && _keys[0] == 'node') {
                nodeids += _keys[1] + ',';
            }
        }

        this.setState({checkedKeys: {checked: _checked, halfChecked: []}, workflowSource: {typeids, flowids, nodeids}});
    }

    getChildrenKeys(children) {
        const keys = [];
        for (let i = 0, len = children.length; i < len; i++) {
            const {key, props} = children[i];

            keys.push(key);
            if (props.children) {
                const keys = this.getChildrenKeys(props.children);
                keys.push(...keys);
            }
        }
        return keys;
    }

    onOk() {
        if (!this.state.title) {
            message.warning(getLabel(15859, '必要信息不完整！'));
        } else {
            const {orderColDataSource:ds, orderColUsedKeys:keys} = this.state;
            const orderColUsed = [];
            for (let i = 0, len = keys.length; i < len; i++) {
                for (let j = 0, len2 = ds.length; j < len2; j++) {
                    if (keys[i] == ds[j].key) {
                        orderColUsed.push(ds[j]);
                    }
                }
            }

            const {workflowSource, isShowNodeBtn, isNeedNode, isExclude} = this.state;
            let {typeids, flowids, nodeids} = workflowSource;
            if(isExclude == '3' || isExclude =='4') {
                flowids = "";
                nodeids="";
            }
            nodeids = (isShowNodeBtn && isNeedNode) ? nodeids : '';
            const eMoreAddress = this.refs['eMoreAddress'] ? this.refs['eMoreAddress'].getSaveValues() : {};
            this.props.onOk(_.omit({...this.state, ...eMoreAddress, orderColUsed, workflowSource: {typeids, flowids, nodeids}}, 'treeData'));
        }
    }

    onCancel() {
        this.props.onCancel();
    }
}

export default Content_8_DataSource;
